package com.lph.health.controller;

import com.lph.health.service.SysUserService;
import com.lph.health.utils.*;
import com.lph.health.vo.MailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 工具控制器
 *
 */
@RestController
@Api(tags = "工具接口")
@RequestMapping("/tool")
public class ToolController {

    @Autowired
    private QiNiuUtil qiNiuUtil;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;
    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "七牛云文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestBody MultipartFile file) throws IOException {
        String url = qiNiuUtil.upLoad(file.getBytes(), file.getOriginalFilename());
        return Result.success("文件上传成功", url);
    }

    @ApiOperation(value = "忘记密码?邮件找回")
    @PostMapping("/forget/password")
    public Result forget(@RequestBody MailVo mailVo) {
        mailVo.setSubject("健康计划定制服务平台");
//        String password = ValidateCodeUtil.generateValidateCode4String(6);
        Integer password = ValidateCodeUtil.generateValidateCode(6);
        mailVo.setContent("您的新密码："+ password +"请妥善保管!");
//        sysUserService.updatePwdByMail(mailVo.getReceivers()[0], passwordEncoder.encode(MD5Util.md5(password));
        sysUserService.updatePwdByMail(mailVo.getReceivers()[0], passwordEncoder.encode(MD5Util.md5(String.valueOf(password))));

        return Result.success("找回密码成功！", mailUtil.sendMail(mailVo));
    }

    @ApiOperation(value = "邮箱验证码")
    @PostMapping("/mailCode")
    public Result mailCode(@RequestBody MailVo mailVo) {
        mailVo.setSubject("健康计划定制服务平台");
        Integer code = ValidateCodeUtil.generateValidateCode(6);
        mailVo.setContent("您的验证码为："+ code +" 有效期为5分钟，请注意使用!");
        String[] receivers = mailVo.getReceivers();
        String mail = receivers[0];
        redisUtil.setValueTime( mail + "code", code, 5);
        return Result.success("验证码发送成功！", mailUtil.sendMail(mailVo));
    }

}
